package net.yebaihe.wc;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import net.yebaihe.wc.DataMan.MSGTYPE;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Invite extends StateMachine{
	private ArrayList<TextView> allTags=new ArrayList<TextView>();
	String currSql;
	private SQLiteDatabase listdb;
	private ListView lstFriends;

	class InviteSimpleCursorAdapter extends SimpleCursorAdapter{

		public InviteSimpleCursorAdapter(Context friends, int itemdish, Cursor c,
				String[] strings, int[] is) {
			super(friends,itemdish,c,strings,is);
		}
		
		@Override  
		public void bindView(View view, Context context, Cursor cursor) {  
			super.bindView(view, context, cursor);
			if (cursor.getPosition() % 2==0){
				//view.setBackgroundColor(R.drawable);
				view.setBackgroundResource(R.drawable.rest_bg_1);
			}
			else{
				//view.setBackgroundColor(0xFFdde4f6);
				view.setBackgroundResource(R.drawable.rest_bg_2);

			}
			ImageView img=(ImageView) view.findViewById(R.id.imagethumb);
			File f=new File(getLocalFriendPath(cursor.getInt(0)));
			if (f.exists()){
				img.setImageBitmap(BitmapFactory.decodeFile(f.getAbsolutePath()));
			}			
		}
	}
	
	public String getLocalFriendPath(int id) {
		String basedir=Environment.getExternalStorageDirectory()+"/weican/users/";
		File f=new File(basedir);
		if (!f.exists()) f.mkdirs();
		//Log.d("", basedir+id+".dat");
		return basedir+id+".dat";
	}

	@Override
	public void HandleMessage(MSGTYPE msgtype, boolean ret,
			HashMap<String, String> params) {
		super.HandleMessage(msgtype, ret, params);
	}

	@Override
	protected String getTopbarTitle() {
		return "邀请好友点餐";
	}

	@Override
	protected void prepareClient(View client) {
		listdb=MyHelper.get(this).getReadableDatabase();
		
		lstFriends=(ListView)client.findViewById(R.id.lstFriends);
		
		UserInfoData userinfo = MyHelper.get(this).getCurrUserInfoData(this.getWCAppContext().email);
		currSql="select * from users where _id in (select touid from friends where fromuid="+userinfo._id+");";
		refreshListFriend();
		
		SQLiteDatabase db = MyHelper.get(this).getReadableDatabase();
		if (db!=null){
			LinearLayout layoutScrollTop=(LinearLayout) client.findViewById(R.id.layoutScrollTop);
			TextView t=addTag("全部",layoutScrollTop);
			t.setBackgroundResource(R.drawable.slide_light);
			Cursor c=db.rawQuery("SELECT distinct friendgroup FROM friends where fromuid="+userinfo._id, null);
			if (c.moveToFirst()){
				do{
					addTag(c.getString(0),layoutScrollTop);
				}while (c.moveToNext());
			}
			c.close();
			db.close();
		}
	}

	private TextView addTag(String string, LinearLayout layoutScrollTop) {
		TextView t=new TextView(this);
		t.setText(string);
		t.setTag(string);
		t.setGravity(Gravity.CENTER);
		allTags.add(t);
		LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.FILL_PARENT);
		p.rightMargin=10;
		p.leftMargin=10;
		t.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				for (int i=0;i<allTags.size();i++){
					allTags.get(i).setBackgroundColor(0x00000000);
				}
				v.setBackgroundResource(R.drawable.slide_light);
				String l=v.getTag().toString();
				UserInfoData userinfo = MyHelper.get(Invite.this).getCurrUserInfoData(Invite.this.getWCAppContext().email);
				if (l.equals("全部")){
					currSql="select * from users where _id in (select touid from friends where fromuid="+userinfo._id+");";
				}
				else{
					currSql="select * from users where _id in (select touid from friends where fromuid="+userinfo._id+" and friendgroup='"+v.getTag().toString()+"');";
				}
				refreshListFriend();
			}
		});
		layoutScrollTop.addView(t,p);
		return t;
	}
	
	protected void onDestroy() {
        super.onDestroy();
        //cursor.close();  //我们在onCreate()中没有关闭游标，因为需要和ListView进行数据关联，关闭curosr，会导致List无数据，故在最后释放资源
        listdb.close(); //断开和数据库的连接，释放相关资源
    }
	
	protected void refreshListFriend() {
		if (listdb!=null){
			Cursor c=listdb.rawQuery(currSql, null);
			startManagingCursor(c);
			ListAdapter listAdapter = new InviteSimpleCursorAdapter(this, R.layout.itemfriendinvite,
					c,
					new String[]{"username"},
					new int[]{R.id.txtname});
			lstFriends.setAdapter(listAdapter);
			lstFriends.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long id) {
					final UserInfoData userdata = MyHelper.get(Invite.this).getCurrUserInfoData(id);
					final UserInfoData mydata = MyHelper.get(Invite.this).getCurrUserInfoData(getWCAppContext().email);
					new AlertDialog.Builder(Invite.this).setIcon(R.drawable.icon).setTitle("邀请好友").setMessage("是否邀请"+userdata.username+"参与聚餐?")
						.setPositiveButton("是", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								int sessionid=Invite.this.getWCAppContext().sessionid;									
								SQLiteDatabase db = MyHelper.get(Invite.this).getWritableDatabase();
								Cursor c=db.rawQuery("select * from sessionuser where uid="+userdata._id+" and sessionid="+sessionid, null);
								if (c.getCount()<=0){
									Toast.makeText(Invite.this, "已发出邀请！", Toast.LENGTH_SHORT).show();
									db.execSQL("insert into sessionuser (sessionid,uid,state) values ("+sessionid+","+userdata._id+",1)");
									Cursor r=db.rawQuery("select * from restaurants where _id in (select restaurant from sessions where _id="+sessionid+")", null);
									r.moveToFirst();
									MyHelper.get(Invite.this).insertNotify(mydata._id, userdata._id, mydata.username+" 邀请您在 "+r.getString(1)+" 聚餐", 1, ""+sessionid+","+r.getLong(0));
									r.close();
								}
								else{
									Toast.makeText(Invite.this, "不能重复发送邀请！", Toast.LENGTH_SHORT).show();
								}	              	 
								c.close();
								db.close();
							}
						}).setNegativeButton("否", null).create().show();
				}
			});
		}
	}

	@Override
	protected int getLayoutRes() {
		return R.layout.invite;
	}

}
